<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

use Session;
use DB;

class WechatAuthCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $wxinfo = Session::get('wxinfo');
		$openid = $wxinfo['openid'];
		if($openid){
			$userinfo = DB::table('staff_openid')->where('wechat_openid',$openid)->first();
			if($userinfo){
				Session::put('userinfo', $userinfo);
			}else{
				return redirect()->to('/bind');
			}
		}else{
			$state = urlencode($request->path());
			$scope_url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxec074239cecd6377&redirect_uri=';
			$scope_url .= urlencode('http://sharing.respimatlibrary.com/wxauth');
			$scope_url .= '&response_type=code&scope=snsapi_userinfo&state='.$state.'#wechat_redirect';
			return redirect()->to($scope_url);
		}
        return $next($request);
    }
}